﻿using Infrastructure.Extensions;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using System;
using System.Collections.Generic;
using System.Text;

namespace Infrastructure
{
    public static class JwtHelper
    {
        /// <summary>
        /// jwt私钥
        /// </summary>
        static string SecretKey
        {
            get
            {
                var jwt = Config.ReadSetting("JWT");
                return string.IsNullOrEmpty(jwt) ? "d#sG3%DfE3=JK0_.x4kez*'Uq|l8,yw]Mn~.?/" : jwt;
            }
        }

        /// <summary>
        /// 创建新token
        /// </summary>
        /// <param name="payload"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">payload 为 null。</exception>
        public static string GenerateToken(Dictionary<string, object> payload, TokenInfo tokenInfo)
        {
            if (payload == null)
                throw new ArgumentNullException(nameof(payload));

            payload.Add("iss", tokenInfo.iss);
            payload.Add("iat", tokenInfo.iat);
            payload.Add("exp", tokenInfo.exp);
            payload.Add("aud", tokenInfo.aud);
            payload.Add("sub", tokenInfo.sub);
            payload.Add("jti", tokenInfo.jti);

            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

            var token = encoder.Encode(payload, SecretKey);
            return token;
        }

        /// <summary>
        /// 解码token
        /// </summary>
        /// <param name="strToken">token字符串</param>
        /// <returns>json内容</returns>
        /// <exception cref="ArgumentNullException">strToken 为 null、空和由空白字符组成。</exception>
        public static string GetDecodingToken(string strToken)
        {
            if (string.IsNullOrWhiteSpace(strToken))
                throw new ArgumentNullException(nameof(strToken));

            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer = new JsonNetSerializer();
            IDateTimeProvider provider = new UtcDateTimeProvider();
            IJwtValidator validator = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);

            var json = decoder.Decode(strToken, SecretKey, true);
            return json;
        }

    }

    public class TokenInfo
    {
        /// <summary>
        /// 实例化签名
        /// </summary>
        /// <param name="iss">jwt签发者</param>
        /// <param name="aud">接收jwt的一方</param>
        /// <param name="sub">jwt所面向的用户</param>
        public TokenInfo(string _iss = "mydefault", string _sub = "token", string _aud = "touser")
        {
            iss = _iss;
            //iat = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
            iat = DateTime.UtcNow.GetTimeStamp();
            exp = iat + 24 * 60 * 60 * 1000; //默认一天过期
            aud = _aud;
            sub = _sub;
            jti = _sub + DateTime.Now.ToString("yyyyMMddhhmmssfff");
        }

        /// <summary>
        /// jwt签发者
        /// </summary>
        public string iss { get; set; }
        /// <summary>
        /// jwt的签发时间
        /// </summary>
        public double iat { get; set; }
        /// <summary>
        /// jwt的过期时间，这个过期时间必须要大于签发时间
        /// </summary>
        public double exp { get; set; }
        /// <summary>
        /// 接收jwt的一方
        /// </summary>
        public string aud { get; set; }
        /// <summary>
        /// 定义在什么时间之前，该jwt都是不可用的
        /// </summary>
        public double nbf { get; set; }
        /// <summary>
        /// jwt所面向的用户
        /// </summary>
        public string sub { get; set; }
        /// <summary>
        /// jwt的唯一身份标识，主要用来作为一次性token，从而回避重放攻击
        /// </summary>
        public string jti { get; set; }
    }


}
